from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from datetime import datetime, timedelta

from blog.models import User


def login_view(request):
    # 检查是否有记住的密码
    if 'remembered_username' in request.session and 'remembered_password' in request.session:
        username = request.session['remembered_username']
        password_hash = request.session['remembered_password']

        # 尝试查找用户
        try:
            user = User.objects.get(username=username)
            # 验证密码
            if check_password(password_hash, user.password):
                # 密码验证成功，可在这里设置登录状态
                request.session['user_id'] = user.id
                return HttpResponseRedirect(reverse('home'))  # 重定向到主页
        except User.DoesNotExist:
            pass  # 处理用户不存在的情况

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        remember = request.POST.get('remember') == 'on'

        try:
            user = User.objects.get(username=username)
            if check_password(password, user.password):
                # 登录成功
                request.session['user_id'] = user.id

                # 处理记住密码
                if remember:
                    # 设置会话有效期为3天
                    request.session['remembered_username'] = username
                    request.session['remembered_password'] = password
                    request.session.set_expiry(259200)  # 3天 = 259200秒
                else:
                    # 清除记住的密码
                    if 'remembered_username' in request.session:
                        del request.session['remembered_username']
                    if 'remembered_password' in request.session:
                        del request.session['remembered_password']

                return HttpResponseRedirect(reverse('home'))  # 重定向到主页
            else:
                return HttpResponse('密码错误')
        except User.DoesNotExist:
            return HttpResponse('用户不存在')

    return render(request, template_name='login.html')


def reg_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print(f'{password}grighri')
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')

        # 使用 Django 内置的密码哈希函数加密密码

        password_hash = make_password(password)
        print(f'{password_hash}grighri')
        print(f"长度{len(password_hash)}")
        # 插入加密后的密码
        User.objects.create(username=username, password=password_hash)
        return HttpResponse('注册成功')
